/*
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements.  See the NOTICE file distributed with
 *   this work for additional information regarding copyright ownership.
 *   The ASF licenses this file to You under the Apache License, Version 2.0
 *   (the "License"); you may not use this file except in compliance with
 *   the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package gateway;

import gateway.plugins.Plugin;
import org.springframework.lang.NonNull;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebHandler;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Objects;


public final class GatewayHandler implements WebHandler{
    private List<Plugin> plugins;//所有插件
    public GatewayHandler(final List<Plugin> plugins) {
        this.plugins = plugins;
    }
    @Override//请求起点
    public Mono<Void> handle(@NonNull final ServerWebExchange exchange) {
        return new DefaultPluginChain(plugins)
                .execute(exchange);
//                .subscribeOn(scheduler)
//                .doOnSuccess(t -> {});
    }
    private static class DefaultPluginChain implements PluginChain, WebMvcConfigurer {
        private int index;
        private final List<Plugin> plugins;
        DefaultPluginChain(final List<Plugin> plugins) {
            this.plugins = plugins;
        }
        @Override//执行路由
        public Mono<Void> execute(final ServerWebExchange exchange) {
            return Mono.defer(() -> {
                if (this.index < plugins.size()) {
                    Plugin plugin = plugins.get(this.index++);
                    //根据请求动态判断是否跳过此插件
                    Boolean skip = plugin.skip(exchange);
                    if (skip) {
                        return this.execute(exchange);
                    } else {
                        return plugin.execute(exchange, this);
                    }
                } else {
                    return Mono.empty();
                }
            });
        }
        @Override//适配MVC语法的HandlerInterceptor
        public void addInterceptors(InterceptorRegistry registry) {
            plugins.forEach(plugin -> {
                if (Objects.nonNull(plugin.getInterceptor())){
                    registry.addInterceptor(plugin.getInterceptor());
                }
            });
        }
    }
}
